/**
 * 目标：解决跨域问题
 * npm i koa
 * npm i koa-router
 * npm i koa2-cors
 */
const Koa = require('koa')
const app = new Koa()

/**
 * 路由之前，解决跨域
 */
// 解决方法1：koa2-cors
// const cors = require('koa2-cors')
// app.use(cors())
// 解决方法2：ctx.set
app.use(async (ctx, next) => {
  ctx.set("Access-Control-Allow-Origin", "*")
  ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  ctx.set("Access-Control-Allow-Methods", "OPTIONS, GET, POST, DELETE, PUT")
  await next()
})

// 引入路由koa-router
const Router = require('koa-router')
const router = new Router()

/**
 * 装载子路由
 * 这里抽离路由模块
 */
const userRouter = require('./router/user')
router.use('/api', userRouter.routes(), userRouter.allowedMethods())

// app加载路由中间件
app.use(router.routes())
app.use(router.allowedMethods())

app.listen(3000, () => {
  console.log('服务器在3000端口运行中...')
})